package com.onpositive.mediawiki.redirects;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.onpositive.wiki3.db.IRedirectAccess;
import com.onpositive.wiki3.db.ITextContentAccess;
import com.onpositive.wiki3.db.ITitleMapper;
import com.onpositive.wiki3.db.IWikiDB;
import com.onpositive.wiki3.db.impl.WikiDBImpl;

public class WikipediaRefsRedirector implements IRefsRedirector {

	IWikiDB wikiDBImpl = new WikiDBImpl("D:/wiki/content");
	IRedirectAccess redirector = wikiDBImpl.getRedirectAccess() ;
	ITextContentAccess accessor = wikiDBImpl.getContentAccessor() ;		
	ITitleMapper titleMapper = wikiDBImpl.getTitleMapper() ;
	

	/* (non-Javadoc)
	 * @see com.onpositive.mediawiki.redirects.IRefsredirector#redirect(com.onpositive.mediawiki.redirects.RefMap)
	 */
	@Override
	public void redirect ( RefMap linksMap){
		
		HashMap<String,Integer> voteMap = new HashMap<String, Integer>() ;
		
		ArrayList<String> redirects = new ArrayList<String>() ;
				
		for( ArrayList<StringPair> arr : linksMap.values() )
		{
			redirects.clear() ;
			for( StringPair sp : arr )
			{
				String value = sp.getValue() ;
								
				String redirected = doRedirect( value, voteMap);				
				
				if( redirected != null  ){
					sp.setValue(redirected) ;
					redirects.add(redirected) ;
				}
			}
		}
		for( String s : redirects )
			linksMap.add(s) ;
	}

	/* (non-Javadoc)
	 * @see com.onpositive.mediawiki.redirects.IRefsredirector#redirect(java.lang.String)
	 */
	@Override
	public String redirect( String str )
	{
		if( str == null || str.length() == 0 )
			return null ;
		
		return doRedirect( str, new HashMap<String,Integer>() ) ;
	}

	private String doRedirect( String value, HashMap<String, Integer> voteMap )
	{
		int[] idArr = titleMapper.getFuzzyMatches(value) ;
		voteMap.clear() ;
		
		for( int id :idArr ){
			
			if( !accessor.hasText(id) )
				continue ;
			
			String refinedTitle = titleMapper.getTitle(id);
			String normalized = redirector.normalizeTitle( refinedTitle ) ;
			if( normalized == null || normalized.length() == 0 )
				continue ;
			
			normalized = normalized.replace(" ", "_") ;
			Integer count = voteMap.get(normalized) ;
			count = count != null ? count + 1 : 1 ;
			voteMap.put(normalized, count) ;					
		}
		int maxCount = -1 ;
		String redirected = null ;
		for( Map.Entry<String, Integer> entry : voteMap.entrySet() )
		{
			if( entry.getValue() > maxCount ){
				redirected = entry.getKey() ;
				maxCount = entry.getValue() ;
			}
		}
		return redirected;
	}
	
}
